'use strict';
const uniID = require('uni-id-common')
exports.main = async (event, context) => {
	const uniIDIns = uniID.createInstance({
		context: context,
	})
	const res = await uniIDIns.checkToken(event.uniIdToken)
	const db = uniCloud.databaseForJQL({
			event,
			context 
		});
		db.setUser({
			role: ['admin']
		})
	let userinfo = await db.collection("uni-id-users").where({
		_id: res.uid
	}).get();
	let pointinfo = await db.collection("pointshop").where({
		_id: event.id
	}).get();
	console.log(pointinfo);
	if(pointinfo.data.length==0){
		return {msg:"id错误",code:400}
	}
	if((userinfo.data[0].point-pointinfo.data[0].price)<0){
		return {msg:"积分不足",code:400}
	}else{
		var vipday;
		if(userinfo.data[0].vip==0||new Date().getTime()>userinfo.data[0].vip){
			vipday=new Date().getTime()+pointinfo.data[0].value*86400000;
		}else{
			vipday=userinfo.data[0].vip+pointinfo.data[0].value*86400000;
		}
		await db.collection("uni-id-users").where({
			_id: res.uid
		}).update({
			vip:vipday,
			point:userinfo.data[0].point-pointinfo.data[0].price
		})
		await db.collection("bill").add({
			time: new Date,
			title: "兑换商品:"+pointinfo.data[0].title,
			content:String(pointinfo.data[0].price),
			user_id: res.uid,
			type: "-",
			bill_type:"point"
		})
		return {msg:"兑换成功",code:200}
	}
	return {msg:"操作成功",code:200}
};